
package core.plugins;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;


/**
 *
 * @author Student
 */
public class EricIDProduct implements IProductIDPlugin 
{
    
    private IProductIDPlugin nextPlugin;
    private int skip = 1;
    
    EricIDProduct()
    {
            nextPlugin = null;
    }

    @Override
    public String idProduct(String barcode) {
        String productDescription = identifyProduct(barcode);
		
		if (productDescription != null)
		{
			return productDescription;
		}
		else
		{
			//get next productID in chain
			IProductIDPlugin next = getNextPlugin();
			if (next != null)
			{
				return next.idProduct(barcode);
			}
			else
			{
				return null;
			}
		}
    }

    @Override
    public void setNextPlugin(IProductIDPlugin nextPlugin) {
        this.nextPlugin = nextPlugin;
    }

    @Override
    public IProductIDPlugin getNextPlugin() {
        return nextPlugin;
    }

    private String identifyProduct(String barcode)
	{
		String url = "http://www.checkupc.com/search.php?keyword="+barcode;
                skip = 1;
		try 
		{
			URL databaseURL = new URL(url);
			BufferedReader in;
			in = new BufferedReader(
				 new InputStreamReader(databaseURL.openStream()));
			

			String inputLine;
			while ((inputLine = in.readLine()) != null)
			{
			        if(inputLine.contains("<strong>") && (skip-- == 0))
			        {
                                    int startIndexx = inputLine.lastIndexOf("<strong>");
                                    int endIndex = inputLine.lastIndexOf("</strong>");
                                    String description = 
                                            (String) inputLine.subSequence(startIndexx, endIndex);
                                    
                                    description = description.substring(8);
                                    
                                    if(description.equals("Your search didn't match any products."))
                                    {
                                        return null;
                                    }
                                    
                                    
                                    
                                    return description;
			        }
			}
			in.close();	
                        
			
		} 
		catch (MalformedURLException e) 
		{
		}
		catch (IOException e) 
		{
		}
        catch(Exception e)
        {
            return null;
        }
		
		return null;
	}
    
}


